package com.teaphy.coroutinecrawler

import kotlinx.coroutines.*

fun main() = runBlocking {
//    testDefault()
//    testAtomic()

//    testLazy()

    testUndispatched()

//    println("end")
}

fun testDefault() {
    println("testDefault - 1")
    val job = GlobalScope.launch(start = CoroutineStart.DEFAULT) {
        // 此处cancel后，testDefault - 2可能是输出不了的，因为可能在协程创建的期间（这里其实是线程池创建期间）就cancel了
        // 也可能输出
        println("testDefault - 2")
    }

    job.cancel()
    println("testDefault - 3")
}

fun testAtomic() {
    println("testAtomic - 1")
    val job = GlobalScope.launch(start = CoroutineStart.ATOMIC) {
        // 此处cancel后，testAtomic - 2是肯定会输出，因为ATOMIC的cancel不能在协程体执行前cancel的
        println("testAtomic - 2")
    }
    job.cancel()
    println("testAtomic - 3")
}

fun testLazy() {
    println("lazy - 1")
    val job = GlobalScope.launch(start = CoroutineStart.LAZY) {
        println("lazy - 2")
    }

    println("lazy - 3")

    // 执行点
    job.start()
    println("lazy - 4")
}

suspend fun testUndispatched() {
    println("undispatched --> 1 threadName: ${Thread.currentThread().name}")

    val job = GlobalScope.launch(start = CoroutineStart.UNDISPATCHED) {
        println("undispatched --> 2 threadName: ${Thread.currentThread().name}")
        // 执行到这里的时候，协程才开始进行线程的创建，执行耗时函数，这里的delay是被suspend标注的函数
        delay(1000)
        println("undispatched --> 3 threadName: ${Thread.currentThread().name}")
    }

    println("undispatched --> 4 threadName: ${Thread.currentThread().name}")
    job.join()

    println("end")
}
